require "digest/sha1"

class User < ActiveRecord::Base
  validates_format_of :name, :with => /[A-Z][a-z]+/
  validates_uniqueness_of :name
  validates_presence_of :name, :password
  before_destroy :dont_destroy_first
  has_one :character

  def before_create
    self.password = encrypt_password(self.password)
  end

  def dont_destroy_first
    if (self.id == 1)
      raise "The first user may not be destroyed."
    end
  end

  def login name, plaintext_password
    plaintext_password ||= ""
    encrypted_password = encrypt_password(plaintext_password)
    User.find(:first, :conditions => ["name = ? and password = ?", name, encrypted_password])
  end

  def try_to_login
    login(name, password)
  end

  def encrypt_password pass
    Digest::SHA1.hexdigest(pass)
  end

end
